import { login, logout, getInfo, refresh, graphic } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name:'',
    nickName: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_NICK_NAME: (state, nickName) => {
    state.nickName = nickName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, verifycode, loginKey } = userInfo // 复制写法，定义从userInfo那里获得对应的值（userInfo里面的对应的key的value）
    return new Promise((resolve, reject) => {
      login({ userName: username.trim(), password: password, verifyCode: verifycode.trim(), loginKey: loginKey.trim(), appId: 'user' }).then(response => {
        commit('SET_TOKEN', response.result)
        setToken(response.result)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const data = response.result
        if (!data) {
          return reject('验证失败，请重新登录')
        }
        const { nickName, userName, icon } = data;
        commit('SET_NAME', userName) // 这里是用户名
        commit('SET_NICK_NAME', nickName) // 这里是用户的昵称
        commit('SET_AVATAR', icon) // 图标
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // 
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // 用refresh_token更新
  refreshToken({commit}){
    return new Promise((resolve, reject) => {
      refresh().then(response =>{
        setToken(response.result)
        commit('RESET_STATE')
        resolve()
      }).catch(error =>{
        reject(error)
      })
    });
  },

  // 获取验证码
  getGraphic(){
    return new Promise((resolve, reject) => {
      graphic().then(response =>{
        resolve(response.result)
      }).catch(error =>{
        reject(error)
      });
    });
  }
  
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

